/*	$Id: error.c 1118 2010-12-12 21:05:32Z phrakt $	*/
/*
 * Copyright (c) 2010 Jean-Francois Brousseau <phrakt@gmail.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL  DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#include "error.h"
#include "private.h"



static const char *cnp_error_msgs[] = {
	"No error",
};




static pthread_key_t    cnp_error_key;


/*
 * cnp_error_init()
 *
 * Initialize the data key that will be used store the thread-specific error
 * code.
 *
 * Returns 0 on success, or -1 on failure.
 */
int
cnp_error_init(void)
{
	if (pthread_key_create(&cnp_error_key, NULL) != 0)
		return (-1);

	return (0);
}

/*
 * cnp_error_cleanup()
 *
 */
void
cnp_error_cleanup(void)
{
	(void)pthread_key_delete(cnp_error_key);
}

/*
 * cnp_error_get()
 *
 * Returns the last error code set for the calling thread.
 *
 */
enum cnp_error
cnp_error_get(void)
{
	enum cnp_error error;

	error = (enum cnp_error)pthread_getspecific(cnp_error_key);

	return (error);
}

/*
 * cnp_error_getmsg()
 *
 * Returns a human-readable error string corresponding to the error code
 * specified in <error>, or NULL if the value of <error> does not represent
 * a valid error code.  The string returned by this function is a constant and
 * MUST NOT be modified.
 */
const char*
cnp_error_getmsg(enum cnp_error error)
{
	if (error >= (sizeof(cnp_error_msgs) / sizeof(cnp_error_msgs[0])))
		return (NULL);

	return (cnp_error_msgs[error]);
}

/*
 * cnp_error_set()
 *
 * Set the calling thread's current error code to the value specified in
 * the argument <error>.
 */
void
cnp_error_set(enum cnp_error error)
{
	(void)pthread_setspecific(cnp_error_key, (void *)error);
}
